import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


def add_prefix(links):
    # 为所有链接添加统一的前缀
    return [(f'https://wz.sun0769.com/{link.url[1:]}') for link in links]

# 需求: 爬取sun中的编号,新闻标题,新闻内容,标号
class SunSpider(CrawlSpider):
    name = "sun"
    # allowed_domains = ["www.xxx.com"]
    start_urls = ["https://wz.sun0769.com/political/index/politicsNewest"]
    # 链接提取器: 根据指定规则(allow=r"正则表达式")进行指定链接的提取
    link = LinkExtractor(allow=r"id=1&page=\d+")
    link_detail = LinkExtractor(allow=r"/political/politics/index?id=\d+")
    rules = (
        # 规则解析器: 将链接提取器提取到的链接进行指定规则(callback)的解析操作
        Rule(link, callback="parse_item", follow=True),
        Rule(link_detail, callback="parse_detail", process_links=add_prefix),
        # follow=True: 可以将链接提取器 继续作用到 链接提取器提取到的链接 所对应的页面中
    )


    # 解析新闻标号和新闻标题
    def parse_item(self, response):
        # xpath表达式中不可以出现tbody标签
        li_list = response.xpath("///html/body/div[2]/div[3]/ul[2]/li")
        for li in li_list:
            num = li.xpath("/html/body/div[2]/div[3]/ul[2]/li[1]/span[1]/text()").extract()[0]
            href = li.xpath('.//a/@href').extract_first()
            title = li.xpath('.//a/text()').extract_first()
            detail_url = 'https://wz.sun0769.com'+href
            # print(num,'***********',detail_url,'**********************',title)
            # scrapy.Request(url=detail_url,callback=self.parse_detail)

    # 解析新闻内容和新闻编号
    def parse_detail(self, response):
        print("****************",response.url)
        new_id = response.xpath("/html/body/div[3]/div[2]/div[2]/div[1]/span[5]/text()").extract_first()
        content = response.xpath("/html/body/div[3]/div[2]/div[2]/div[2]/pre/text()").extract_first()
        print(new_id, "          " ,content)